package com.mars.deepseek.service.impl;

import com.alibaba.fastjson.JSON;
import com.mars.deepseek.config.DeepSeekConfig;
import com.mars.deepseek.exception.DeepSeekException;
import com.mars.deepseek.model.dto.ChatRequest;
import com.mars.deepseek.model.dto.ChatResponse;
import com.mars.deepseek.service.DeepSeekService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * DeepSeek API服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeepSeekServiceImpl implements DeepSeekService {

    private final OkHttpClient okHttpClient;
    private final DeepSeekConfig.DeepSeekProperties properties;

    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

    /**
     * 聊天接口路径
     */
    private static final String CHAT_ENDPOINT = "/v1/chat/completions";

    @Override
    public ChatResponse chat(ChatRequest request) {
        // 设置默认模型
        if (!StringUtils.hasText(request.getModel())) {
            request.setModel(properties.getModel());
        }

        // 构建请求URL
        String requestUrl = properties.getBaseUrl() + CHAT_ENDPOINT;
        // 构建请求体
        String requestBody = JSON.toJSONString(request);

        // 构建请求
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, requestBody);
        Request httpRequest = new Request.Builder()
                .url(requestUrl)
                .addHeader("Authorization", "Bearer " + properties.getApiKey())
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();

        try {
            // 发送请求
            Response response = okHttpClient.newCall(httpRequest).execute();

            // 检查响应状态
            if (!response.isSuccessful()) {
                String errorBody = Objects.requireNonNull(response.body()).string();
                log.error("DeepSeek API调用失败: {}", errorBody);
                throw new DeepSeekException(response.code(), "DeepSeek API调用失败: " + errorBody);
            }

            // 解析响应
            String responseBody = Objects.requireNonNull(response.body()).string();
            log.debug("DeepSeek API响应: {}", responseBody);

            return JSON.parseObject(responseBody, ChatResponse.class);
        } catch (IOException e) {
            log.error("DeepSeek API调用异常", e);
            throw new DeepSeekException("DeepSeek API调用异常: " + e.getMessage(), e);
        }
    }
}
